package com.cloudlinkscm.base.authcenter.common;

import com.cloudlinkscm.base.authcenter.model.UserAccount;
import com.cloudlinkscm.base.authcenter.model.dto.AccessToken;
import com.cloudlinkscm.loms.redis.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Created by sin on 2017/7/27.
 */
@Service
public class RedisManager {

	@Autowired
	private RedisClient redisClient;

	/**
	 * 账户 - cache 超时时间 30 秒
	 */
	private static final Long USER_ACCOUNT_TIMEOUT = 60L * 30L;


	public AccessToken cacheUserAccount(String token, UserAccount userAccount) {
		redisClient.setObject(token, userAccount, USER_ACCOUNT_TIMEOUT, TimeUnit.SECONDS);
		long cacheStartTime = System.currentTimeMillis();
		long cacheExpirationTime = System.currentTimeMillis() + USER_ACCOUNT_TIMEOUT * 1000;
		return AccessToken.Build(token, USER_ACCOUNT_TIMEOUT, cacheStartTime, cacheExpirationTime);
	}

	public UserAccount getUserAccount(String token) {
		try {
			return (UserAccount) redisClient.getObject(token);
		} catch (IllegalArgumentException e) {
			// skip
			return null;
		}
	}
}
